<?php
namespace app\index\model;
use think\Db;
use think\Model;
use app\atxunda\model\SubQuestion as QuesAdmin;

class SubQuestion extends Model
{
	public function getTypeDataQuesIds($typeIds, $field = 'type_id'){
		return self::where($field,'in',$typeIds)->column('id');
	}

	public function getQuesOne($id){
		$data = self::field('id,seek,course_id,stem,metas,analysis,answer,nav_id')->where('id',$id)->find();
		if(!$data) return [];
		$data['stem'] = str_replace('/public', 'http://www.xunda.com/public', $data['stem']);
		$data['answer'] = json_decode($data['answer'],true);
		$data['metas'] = QuesAdmin::choicesDispose($data['metas']);
		return $data;
	}

	public function disposeUserAnswer($tId,$id,$answer,$helper = 0){
		self::where('id',$id)->setInc('visits');
		$data = self::field('id,seek,course_id,stem,metas,answer,type')->where('id',$id)->find();
		if(!$data) return [];
		$data['answer'] = json_decode($data['answer'],true);
		if(!is_array($answer)) $answer = [0=>$answer];
		if($data['answer'] == $answer){
			$status = 1;
			if ($helper == 0) $action = 'delete';
		}else{
			$status = 2;
			$action = 'insert';
		}
		SubUserInfo::disposeWrong(2, $id,$action);
		SubUser::disposeUserQues($tId, $id, $answer, $status);
		return [
			'tId' => $tId,
			'status' => $status,
			'seek' => $data['seek'],
		];
	}

	public function getQuesByIds($ids, $type = 1){
		$user = user();
		if(empty($ids)) return [];
		return self::field('sub_question.id,stem,nav_top_title,course_name')
					->where('sub_question.id','in',$ids)
					->join('nav','nav.nav_id=sub_question.nav_id')
					->join('course','course.course_id=sub_question.course_id')
					->when($user, function($query) use($user,$type){
						$query->field("FROM_UNIXTIME(last_time,'%Y-%m-%d %H:%i:%s') as time")->join('sub_user_info','ques_id=sub_question.id')->where('user_id',$user['id'])->where('sub_user_info.type',$type)->order('last_time desc');
					})->order("field(sub_question.id,".implode(',',$ids).")")->paginate(10);
	}
}